package com.example.controller;

import com.example.pojo.*;
import com.example.service.MedicalService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/medical")
public class MedicalController {

    @Autowired
    private MedicalService medicalService;

    @RequestMapping("/getList")
    public Result getList(@RequestBody ConditionsQuery conditionsQuery){

        PageHelper.startPage(conditionsQuery.getPageNum(),conditionsQuery.getPageSize());

        List<DrugVo> list=medicalService.getList(conditionsQuery);
        // System.err.println(list);

        PageInfo<DrugVo> pageInfo=new PageInfo<>(list);

        Map<String,Object> resultMap=new HashMap<>();

        //当前页数据
        resultMap.put("list",pageInfo.getList());

        //数据总数
        resultMap.put("total",pageInfo.getTotal());

        return new Result(200,"数据加载成功",resultMap);
    }

    @RequestMapping("/getSaleListByPage")
    public Result getSaleListByPage(@RequestBody BaseQuery baseQuery){
        PageHelper.startPage(baseQuery.getPageNum(),baseQuery.getPageSize());

        List<Sale> list=medicalService.getSaleList();
        // System.err.println(list);

        PageInfo<Sale> pageInfo=new PageInfo<>(list);

        Map<String,Object> resultMap=new HashMap<>();

        //当前页数据
        resultMap.put("list",pageInfo.getList());

        //数据总数
        resultMap.put("total",pageInfo.getTotal());

        return new Result(200,"数据加载成功",resultMap);

    }
    @RequestMapping("/getSaleList")
    public Result getSaleList(){

        List<Sale> list=medicalService.getSaleList();
        // System.err.println(list);
        return new Result(200,"数据加载成功",list);

    }
    @RequestMapping("/getMarker")
    public Result getMarker(){
        return medicalService.getMarker();
    }

    @RequestMapping("/upload")
    public Result upload(MultipartFile file) {

        System.err.println(file);
        if(file==null){
            System.err.println(1111);
            return new Result(505,"1",null);
        }
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename );
        System.err.println(file);
        String fileName = file.getOriginalFilename();
        // 生成新的文件名，通过添加时间戳来确保唯一性
        String newFileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
        // 定义文件存储路径
        String path = "D:\\upload5";

        // 创建文件对象
        File f = new File(path);
        // 如果路径不存在，则创建它
        if (!f.exists()) {
            f.mkdirs();
        }

        try {
            // 将上传的文件转移到指定的路径和新文件名
            file.transferTo(new File(path + File.separator + newFileName));
            // 构建文件的URL地址
            String url = "http://localhost:8085/" + newFileName;
            //String url = "http:// 192.168.227.98:8082/" + newFileName;
            // 返回上传成功的结果
            return new Result(200, "文件上传成功", url);
        } catch (IOException e) {
            // 如果发生IO异常，抛出运行时异常
            throw new RuntimeException(e);
        }
    }

    /**
     * ！！！   从请求体中获取销售ID字符串
     *         String ids =map.get("saleIds");
     *         String[] idStr =ids.split(",");
     * @param map
     * @param request
     * @return
     */
    @RequestMapping("/add")
    public Result add(@RequestBody Map<String, String> map, HttpServletRequest request) {
        // 创建Drug对象并设置属性
        Drug drug = new Drug();
        drug.setDrug_name(map.get("drug_name"));
        drug.setDrug_info(map.get("drug_info"));
        drug.setDrug_effect(map.get("drug_effect"));
        drug.setDrug_img(map.get("drug_img"));

        // 从请求体中获取销售ID字符串
        String ids =map.get("saleIds");
        String[] idStr =ids.split(",");
System.err.println(map);
        List<Integer> idList=new ArrayList<>();

        for (int i=0; i<idStr.length;i++){
            idList.add(Integer.parseInt(idStr[i]));
        }
        // 从请求头中获取token
        String token = request.getHeader("token");

        // 调用服务层方法添加药品，并返回结果
        return medicalService.add(drug, idList, token);
    }

    /**
     * ！！！   从请求体中获取销售ID字符串
     *         String ids =map.get("saleIds");
     *         String[] idStr =ids.split(",");
     * @param map
     * @param request
     * @return
     */
    @RequestMapping("/edit")
    public Result edit(@RequestBody Map<String, String> map, HttpServletRequest request) {
        // 创建Drug对象并设置属性
        Drug drug = new Drug();
        drug.setDrug_id(Integer.parseInt(map.get("drug_id")));
        drug.setDrug_name(map.get("drug_name"));
        drug.setDrug_info(map.get("drug_info"));
        drug.setDrug_effect(map.get("drug_effect"));
        drug.setDrug_img(map.get("drug_img"));

        // 从请求体中获取销售ID字符串
        String ids =map.get("saleIds");
        String[] idStr =ids.split(",");

        List<Integer> idList=new ArrayList<>();

        for (int i=0; i<idStr.length;i++){
            idList.add(Integer.parseInt(idStr[i]));
        }
        // 从请求头中获取token
        String token = request.getHeader("token");

        // 调用服务层方法修改药品，并返回结果
        return medicalService.edit(drug, idList, token);
    }
    @RequestMapping("/delDrugById")
    public Result delDrugById(@RequestBody Map<String, String> map,HttpServletRequest request){
        // 从请求头中获取token
        String id=map.get("id");
        String token = request.getHeader("token");

        // 调用服务层方法修改药品，并返回结果
        return medicalService.delDrugById(id, token);
    }

    /**
     * 药品批量删除（2025.1.8修正）
     * @param map
     * @param request
     * @return
     */
    @RequestMapping("/delBatch")
    public Result delBatch(@RequestBody Map<String,String> map,HttpServletRequest request){

        String ids = map.get("ids");
        // 从请求头中获取token
        String token = request.getHeader("token");
        return medicalService.delBatch(ids,token);
    }
}
